/**
 * 出港速运行李管理
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Modal, DatePicker, Select, message, Input } from 'antd';
import ProTable from '@ant-design/pro-table';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';
import { fileDownload } from '@/utils/downExcel';
import { useActivate } from 'react-activation';

import {
  getUserServiceCity,
  expressTransportationPage,
  selectCityInfo,
  expressTransportationDelete,
  expressTransportationExport
} from './service';
import { Const } from '../Const';

import AuthComponent from '@/components/Authorized/AuthComponent';

const { Option } = Select;

class PrivateData {
  static ownerType = 8;
  static isFirst = true;
  static toolBarRenderArr = [
    { text: '新增', value: '1', authCode: 'outLuggage.basicPermissions', disabled: false },
    // { text: '修改', value: '2', authCode: 'XXX', disabled: false },
    { text: '删除', value: '3', authCode: 'outLuggage.deleteIncident', disabled: false },
    { text: '导出excel', value: '4', authCode: 'outLuggage.basicPermissions', disabled: false },
    { text: '打印', value: '5', authCode: 'outLuggage.basicPermissions', disabled: false },
  ];
}

const QuickBaggageManagement = props => {

  const { location: { state } } = props;

  const actionRef = useRef();
  const ref = useRef();

  const [height, controlH] = useState(300); // table高度
  const [isCollapse, controlC] = useState(true);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  const [userServiceCity, setUserServiceCity] = useState('');

  const [searchData, setSearchData] = useState({});

  // 表格是否有数据
  const [exportFlag, handleExportFlag] = useState(false);

  const [createStartTime, setCreateStartTime] = useState(''); // 开始时间
  const [createEndTime, setCreateEndTime] = useState(''); // 结束时间

  // 重新加载
  const reloadReset = () => {
    setSelectedRows([]);
    setSelectedRowKeys([]);
    // actionRef.current.reload();
    ref.current.submit();
  };

  // 导出
  const { run: runExpressTransportationExport } = useRequest(params => expressTransportationExport(params), {
    manual: true,
    onSuccess(res) {
      fileDownload(res, '出港速运行李管理');
    }
  })

  // 航站下拉列表
  const { data: selectCityData = [] } = useRequest(selectCityInfo);

  // 获取登录用户所属航站
  const { run: runGetUserServiceCity } = useRequest(getUserServiceCity, {
    onSuccess (res) {
      console.log(res, '获取登录用户所属航站');
      let data = res.serviceCity || '';
      setUserServiceCity(data);
    }
  });

  // 删除
  const { run: runExpressTransportationDelete } = useRequest(data => expressTransportationDelete(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '删除');
      reloadReset();
    }
  })

  // 编辑过后页面可见重新请求下列表数据
  useActivate(() => {
    if (Const.getIsNeedGetList(PrivateData.ownerType)) reloadReset();
  });

  useEffect(() => {
    if (PrivateData.isFirst) {
      setTimeout(() => {
        ref.current.setFieldsValue({
          newFlightDate: moment(),
          oldFlightDate: moment(),
        })
      }, 0);
    }
    return () => {
      PrivateData.isFirst = true;
    };
  }, []);

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 370);
    } else {
      controlH(document.body.clientHeight - 470);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isCollapse]);

  const disabledStartDate = useCallback((current) => {
    if (createEndTime) return current && (current > moment(createEndTime).endOf('day'));
    return false;
  }, [createEndTime]);

  const disabledEndDate = useCallback((current) => {
    if (createStartTime) return current && (current < moment(createStartTime).startOf('day'));
    return false;
  }, [createStartTime]);


  // rowSelection
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  // 重置
  const onReset = useCallback(() => {
    PrivateData.isFirst = true;
    setTimeout(() => {
      ref.current.setFieldsValue({
        newFlightDate: moment(),
        oldFlightDate: moment()
      });
    }, 0)
  }, []);

  const goToDetail = useCallback((record) => {
    router.push({
      pathname: Const.commonUrl + '/outPortBaggageManagement/incidentDetail',
      state: {
        id: record.id || ''
      }
    })
  }, []);

  // 顶部点击事件
  const headerTitleClick = useCallback(val => {
    if (val === '1') {
      router.push({
        pathname: Const.commonUrl + '/outPortBaggageManagement/addEditIncident',
        state: {
          selectCityData,
          userServiceCity,
          type: 'add',
          id: ''
        }
      })
    }
    // if (val === '2') {
    //   if (selectedRows.length === 1) {
    //     router.push({
    //       pathname: Const.commonUrl + '/outPortBaggageManagement/addEditIncident',
    //       state: {
    //         selectCityData,
    //         userServiceCity,
    //         type: 'edit',
    //         id: selectedRows[0].id
    //       }
    //     })
    //   } else {
    //     message.warning('请选择一个事故单');
    //   }
    // }
    if (val === '3') {
      if (selectedRows.length === 1 && (!(selectedRows[0].type === '6' || selectedRows[0].type === '多收转速运'))) {
        Modal.confirm({
          title: '确认删除',
          content: '删除该条记录',
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            console.log('确认删除');
            runExpressTransportationDelete([selectedRows[0].id])
          }
        });
      } else {
        message.warning('请选择一个速运类型不是多收转速运的进行删除');
      }
    }
    if (val === '4') {
      if (!exportFlag) {
        message.warning('表格数据为空');
        return
      }
      runExpressTransportationExport({...searchData})
    }
    if (val === '5') {
      if (selectedRows.length === 1) {
        router.push({
          pathname: Const.commonUrl + '/outPortBaggageManagement/printPage',
          state: {
            accidentId: selectedRows[0].id,
            ownerType: PrivateData.ownerType
          }
        });
      } else {
        message.warning('请选择一个事故单')
      }
    }
  }, [selectCityData, userServiceCity, selectedRows, searchData, exportFlag]);

  const columns = [
    {
      title: '速运行李编号',
      dataIndex: 'expressTransportationNo',
      width: 200,
      fixed: 'left',
      hideInSearch: true,
      render: (text, record) => <Button type="link" style={{ padding: '0' }} onClick={() => goToDetail(record)}>{text}</Button>
    },
    {
      title: '创建航站',
      dataIndex: 'createTerminal',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '始发站',
      dataIndex: 'org',
      width: 80,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '目的站',
      dataIndex: 'dst',
      width: 80,
      renderFormItem: (_, { onChange, value }) => (
        <Select
          allowClear
          showSearch
          placeholder="请选择"
          value={value}
          onChange={onChange}
          optionFilterProp="children"
        >
          {selectCityData.map(({ CITYNAME, CITY3CODE }) => <Option key={CITY3CODE} value={CITY3CODE}>{CITYNAME}-{CITY3CODE}</Option>)}
        </Select>
      ),
    },
    {
      title: '新行李牌号',
      dataIndex: 'newPkgNo',
      width: 120,
    },
    {
      title: '新航班号',
      dataIndex: 'newFlightNo',
      width: 100,
      renderFormItem: (_, { value, onChange }) => {
        return <Input
          onChange= {e => {
            let value = Const.formatFlightNo(e.target.value);
            onChange(value);
          }}
          value={value}
          allowClear
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '新航班日期',
      dataIndex: 'newFlightDate',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={onChange}
            value={value}
          />
        );
      }
    },
    {
      title: '旧行李牌号',
      dataIndex: 'oldPkgNo',
      width: 120,
    },
    {
      title: '旧航班号',
      dataIndex: 'oldFlightNo',
      width: 100,
      renderFormItem: (_, { value, onChange }) => {
        return <Input
          onChange= {e => {
            let value = Const.formatFlightNo(e.target.value);
            onChange(value);
          }}
          value={value}
          allowClear
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '旧航班日期',
      dataIndex: 'oldFlightDate',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={onChange}
            value={value}
          />
        );
      }
    },
    {
      title: '速运类型',
      dataIndex: 'type',
      width: 100,
      valueEnum: Const.suYunTypeMap,
      filters: false,
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '行李航程',
      dataIndex: 'voyage',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '行李重量',
      dataIndex: 'weight',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '创建开始时间',
      dataIndex: 'createDateStart',
      width: 100,
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateStartTime(val);
              onChange(val);
            }}
            disabledDate={disabledStartDate}
            value={value}
          />
        );
      }
    },
    {
      title: '创建结束时间',
      dataIndex: 'createDateEnd',
      width: 100,
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={Const.format}
            onChange={val => {
              setCreateEndTime(val);
              onChange(val);
            }}
            disabledDate={disabledEndDate}
            value={value}
          />
        );
      }
    },
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        className={styles.compactTable}
        rowKey="id"
        rowSelection={rowSelection}
        headerTitle="出港速运行李管理"
        toolBarRender={() => PrivateData.toolBarRenderArr.map((item, index) => (
          <AuthComponent authCode={item.authCode} key={index}>
            <Button
              type="primary"
              disabled={item.disabled}
              size="small"
              onClick={() => headerTitleClick(item.value)}>
              {item.text}
            </Button>
          </AuthComponent>
        ))}
        onSubmit={() => {
          setSelectedRowKeys([]);
          setSelectedRows([]);
        }}
        onReset={onReset}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          if (PrivateData.isFirst) {
            params.newFlightDate = moment().format(Const.format);
            params.oldFlightDate = moment().format(Const.format);
            PrivateData.isFirst = false;
          } else {
            let arr = ['newFlightDate', 'oldFlightDate', 'createDateStart', 'createDateEnd'];
            for (let item of arr) {
              if (params[item] && params[item].isValid()) {
                params[item] = moment(params[item]).format(Const.format)
              }
            }
          }
          setSearchData(params);
          return expressTransportationPage(params);
        }}
        tableAlertRender={false}
        columns={columns}
        options={false}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
        }}
        scroll={{ x: 900, y: height }}
        search={{
          onCollapse: val => {
            controlC(val);
          },
          span: { // 设置排列方式
            xs: 24,
            sm: 24,
            md: 6,
            lg: 6,
            xl: 6,
            xxl: 6,
          }
        }}
      >
      </ProTable>
    </>
  )
}

export default Form.create()(QuickBaggageManagement);
